package testJdk.io.nioTester;

import java.io.IOException;
import java.nio.file.*;

/**
 * @Name : com.io.nioTester.TestMul
 * @Description : 描述
 * Created by cyd on 2020-12-23 13:48:08
 */
public class FilesTool {

    public void copyFile(String fromDir,String toDir,String file) throws IOException {
        Path pathFrom = Paths.get(fromDir, new String[]{file});
        Path pathTo = Paths.get(toDir, new String[]{file});
        // 调用复制文件的方法，如果目标文件已经存在，就将其覆盖
        Files.copy(pathFrom,pathTo, StandardCopyOption.REPLACE_EXISTING);
    }

    public void moveFile(String fromDir,String toDir,String file) throws IOException {
        Path pathFrom = Paths.get(fromDir, new String[]{file});
        Path pathTo = Paths.get(toDir, new String[]{file});
        System.out.println("--------文件的大小-----------");
        System.out.println(Files.size(pathFrom));
        // 移动，如果有就覆盖
        Files.move(pathFrom,pathTo,StandardCopyOption.REPLACE_EXISTING);
    }

    public void creatAndShowDir(String dir) throws IOException {
        Path path = Paths.get(dir);
        // 创建文件夹
        if (Files.notExists(path)){
            Files.createDirectories(path);
            System.out.println("create Directories");
        }else {
            System.out.println("Directories exists");
        }

        // 遍历文件夹下面的文件
        DirectoryStream<Path> paths = Files.newDirectoryStream(path);
        for (Path p:paths){
            System.out.println(p.getFileName());
        }

        System.out.println("---------过滤文件---------");
        // 创建一个带有过滤器的目录流，过滤条件为：文件名+后缀
        DirectoryStream<Path> pathsStream = Files.newDirectoryStream(path, "*.{java,txt,bat}");
        for (Path p:pathsStream){
            System.out.println(p.getFileName());
        }
    }

    public static void main(String[] args) throws IOException {
        FilesTool filesTool = new FilesTool();

        // 将D盘根目录下的hello.txt，复制到D:\ioTester路径下
        filesTool.copyFile("D:\\","D:\\ioTester\\","hello.txt");
        // 遍历循环
        filesTool.creatAndShowDir("D:\\");
        // 移动文件
        filesTool.moveFile("D:\\","D:\\ioTester\\","readme.txt");
    }
}
